package com.sh.data.engine.domain.datadev.offline.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sh.data.engine.domain.datadev.offline.service.DatadevJobService;
import com.sh.data.engine.domain.datadev.offline.service.OfflineDevMenuNodeService;
import com.sh.data.engine.job.core.context.XxlJobHelper;
import com.sh.data.engine.job.core.handler.annotation.XxlJob;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevMenuNodeEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: zigui.zdf @Date: 2022/2/24 16:34:49 @Description:
 */
@Component
@Slf4j
public class OfflineDevTask {

    @Autowired
    private DatadevJobService datadevJobService;

    @Autowired
    private OfflineDevMenuNodeService offlineDevMenuNodeService;

    /**
     * 不需要手动添加到xxl-info
     */
    @XxlJob(value = "OfflineDevTask")
    public void run() {
        final long jobId = XxlJobHelper.getJobId();
        final String jobParam = XxlJobHelper.getJobParam();

        final DatadevMenuNodeEntity taskFlowId =
            offlineDevMenuNodeService.findByXxlJobId(Math.toIntExact(jobId));

        if (null == taskFlowId) {
            XxlJobHelper.log("xxl-job id:{}对应的数据集成引擎中的任务不存在，执行结束....", jobId);
            return;
        }

        XxlJobHelper.log("任务拉起，开始异步执行");

        int execType = 1;
        if (StringUtils.isNotBlank(jobParam)) {
            final JSONObject jsonObject = JSON.parseObject(jobParam);
            execType = jsonObject.getIntValue("execType");
        }

        datadevJobService.startTaskFlowJob(
            taskFlowId.getId(), execType, taskFlowId.getProjectId(), taskFlowId.getCreatorId());
    }
}
